package com.i2863.shiroDemo.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.i2863.shiroDemo.web.BaseController;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;

@Controller
@RequestMapping(value = "/file", produces = "text/html;charset=UTF-8")
public class UploadFileUtil extends BaseController {

    private Gson gson = new Gson();

    private final static String[] IMAGETYPES = {"jpg", "png", "gif", "bmp", "jpeg"};

    private final static List<String> TYPELIST = Arrays.asList(IMAGETYPES);

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, String relativePath) {
        Map<String, Object> data = new HashMap<>(8);

        if (file.isEmpty()) {
            data.put("code", 1);
            data.put("msg", "文件为空");
        }
        //图片上传七牛
        try {
            Map<String, Object> map = QiNiuUtil.getUploadManagerForSiteid(136);
            UploadManager uploadManager = (UploadManager) map.get("uploadManager");
            String host = (String) map.get("host");
            Response res = uploadManager.put(file.getBytes(), relativePath, (String) map.get("token"));
            String body = res.bodyString();
            JsonObject object = JsonParser.parseString(body).getAsJsonObject();
            String imgPath = "http://" + host + "/" + object.get("key").getAsString();
            data.put("code", 0);
            data.put("msg", "上传成功");
            data.put("path", imgPath);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
            data.put("code", 1);
            data.put("msg", "上传出错");
        }
        return gson.toJson(data);
    }


    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        Map<String, Object> data = new HashMap<>(8);

        if (file.isEmpty()) {
            data.put("code", 1);
            data.put("msg", "文件为空");
        }

        String fileName = file.getOriginalFilename();
        String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".") + 1);
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

        //图片上传七牛
        try {
            Map<String, Object> map = QiNiuUtil.getUploadManagerForSiteid(127);
            UploadManager uploadManager = (UploadManager) map.get("uploadManager");
            String host = (String) map.get("host");
            Response res = uploadManager.put(file.getBytes(), newFileName, (String) map.get("token"));
            String body = res.bodyString();
            JsonObject object = JsonParser.parseString(body).getAsJsonObject();
            String imgPath = "http://" + host + "/" + object.get("key").getAsString();
            data.put("code", 0);
            data.put("msg", "上传成功");
            data.put("path", imgPath);
            if (TYPELIST.contains(suffix.toLowerCase())) {
                data.put("type", 0);
            } else {
                data.put("type", 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
            data.put("code", 1);
            data.put("msg", "上传出错");
        }
        return gson.toJson(data);
    }

    /**
     * 生成缩略图
     *
     * @param url    原图url
     * @param width  缩略图宽
     * @param height 缩略图高
     * @return
     * @throws IOException
     */
    public static byte[] getThumbImageByte(String url, int width, int height) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            Thumbnails.of(new URL(url)).size(width, height).toOutputStream(baos);
            return baos.toByteArray();
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成缩略图
     *
     * @param url  原url
     * @param rate 比例
     * @return
     * @throws IOException
     */
    public static byte[] getThumbImageByte(String url, double rate) throws IOException {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            Thumbnails.of(new URL(url)).scale(rate).toOutputStream(baos);
            return baos.toByteArray();
        } finally {
            try {
                Objects.requireNonNull(baos).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
